$(function() {
    getUserinfo()


    //退出按钮
    let layer = layui.layer
    $('#btnLogout').on('click', function() {
        layer.confirm('是否确定退出?', { icon: 3, title: '提示' }, function(index) {
            //do something
            //清楚本地存储的token
            localStorage.removeItem('token')
                // 跳转到login登录页面
            location.href = '../../login.html'
                //关闭弹出层
            layer.close(index);
        });
    })
})

function getUserinfo() {
    $.ajax({
        url: '/my/userinfo',
        method: 'GET',
        // headers: { Authorization: localStorage.getItem('token') || '' },
        success: function(res) {
            console.log(res);
            if (res.code !== 0) {
                return layui.layer.msg('信息获取失败')
            }
            //渲染头像和名字
            render(res.data)
        },
        //不论成功还是失败都会调用complete方法，它是ajax的一个内置方法
        // complete: function(res) {
        //     console.log(res);

        //     if (res.responseJSON.code === 1 && res.responseJSON.message === '身份认证失败！') {
        //         //清楚本地存储的token
        //         localStorage.removeItem('token')
        //             // 跳转到login登录页面
        //         location.href = '../../login.html'
        //     }
        // }
    })
}

function render(data) {
    let name = data.nickname || data.username
    $('#welcome').html(name)

    if (data.user_pic !== null) {
        $('.layui-nav-img').attr('src', data.user_pic).show()

        $('.text-avatar').hide()
    } else {
        let First = name[0].toUpperCase()
        $('.layui-nav-img').hide()
        $('.text-avatar').html(First).show()
    }

}